import {Component} from 'react';
import React from 'react';
import $ from 'jquery';
import ReactPaginate from 'react-paginate';
import {ClonePair} from "./ClonePair";

export default class ClonePairList extends Component{
    constructor(props){
        super(props);
        this.state = {
            clonePairUrl : "http://localhost:8080/pair/detail",
            cloneTaskId : this.props.taskId,
            cloneType: this.props.cloneType,
            totalPairsNum : this.props.totalNum,
            selectedPage : 1,
            totalPage : Math.ceil(this.props.totalNum / 10),
            pairDetail :[],
            isPageChanged : false
        }
    }
    componentWillReceiveProps(){

    }

    componentDidMount(){
        this.loadPairInfoFromServer();
    }

    loadPairInfoFromServer(){
        let url = this.state.clonePairUrl;
        let data = {
            "taskId" : this.state.cloneTaskId,
            "cloneType" : this.state.cloneType,
            "page" : this.state.selectedPage
        };
        $.ajax({
            url: url,
            data : JSON.stringify(data),
            contentType : "application/json",
            dataType : "json",
            type :"post",
            success : result =>{
                this.setState({
                    pairDetail : result.data
                })
            },
            error: (xhr,status, err) =>{
                console.error(url, status, err.toString());
            }
        })
    }

    handlePageClick=(data)=>{
        let selecetd = data.selected;
        selecetd += 1;
        this.setState({
            selectedPage : ""+selecetd,
        },()=>{
            this.loadPairInfoFromServer();
        });
    };

    render(){
        let pairInfoList = this.state.pairDetail.map((pair) => {
            return <ClonePair data={pair}/>
        });
        return (
            <div className="col-md-12 column">
                <div className="data-div">
                    <div className="tablebody">
                        <div>
                            {pairInfoList}
                        </div>
                    </div>
                </div>
                <ReactPaginate previousLabel={"previous"}
                               nextLabel={"next"}
                               breakLabel={<a href="">...</a>}
                               breakClassName={"break-me"}
                               pageCount={this.state.totalPage}
                               marginPagesDisplayed={2}
                               pageRangeDisplayed={5}
                               onPageChange={this.handlePageClick}
                               containerClassName={"pagination"}
                               subContainerClassName={"pages pagination"}
                               activeClassName={"active"} />
            </div>
        )
    }
}